package com.longcai.cm.moudules.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.cm.base.aop.Log;
import com.longcai.cm.base.bean.PageVo;
import com.longcai.cm.base.bean.Pageable;
import com.longcai.cm.bean.R;
import com.longcai.cm.common.utils.RequestUtil;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.moudules.system.domain.SysRoleMenus;
import com.longcai.cm.moudules.system.domain.SysRoles;
import com.longcai.cm.moudules.system.service.SysRoleMenusService;
import com.longcai.cm.moudules.system.service.SysRolesService;
import com.longcai.cm.utils.DateUtils;
import com.longcai.cm.moudules.system.utils.UUID;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sysRoles")
@Api(value = "系统管理-角色", tags = "系统管理-角色")
@ApiSort(2)
public class SysRolesController {

    @Resource
    private SysRolesService sysRolesService;

    @Resource
    private SysRoleMenusService sysRoleMenusService;


    /**
     * 【API】-----【S2001】
     * 获取角色列表分页数据
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */

    @Log(value = "获取角色列表", type = "1")
    @PostMapping("/getList")
    @RequiresPermissions("roleList:list")
    public R getList(HttpServletRequest request, HttpServletResponse response) {

        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<SysRoles> result = sysRolesService.getPageBean(pageInfo, SysRoles.class);

        return R.success(result);
    }


    /**
     * 【API】-----【S2005】
     * 保存角色信息（同时保存权限相关信息）
     *
     * @param sysRoles 表单信息
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return R
     */
    @Log(value = "保存角色信息", type = "1")
    @PostMapping(value = "/save")
    public R save(SysRoles sysRoles, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String id = sysRoles.getId();
        if (id != null && id != "") {
            sysRolesService.updateById(sysRoles);
        } else {
            sysRoles.setId(UUID.get());
            sysRolesService.save(sysRoles);
        }

        // 先删除之前的关联关系
        QueryWrapper<SysRoleMenus> eWrapper = new QueryWrapper<>();
        eWrapper.eq("role_id", sysRoles.getId());
        sysRoleMenusService.remove(eWrapper);


        String menuIdsString = request.getParameter("menuIds");
        if (StringUtils.isNotBlank(menuIdsString)) {
            List<String> menuIdList = JSON.parseArray(menuIdsString, String.class);
            for (String menuId : menuIdList) {
                SysRoleMenus rmMenus = new SysRoleMenus();
                rmMenus.setId(UUID.get());
                rmMenus.setMenuId(menuId);
                rmMenus.setRoleId(sysRoles.getId());
                rmMenus.setUpdateTime(DateUtils.getTimeNow());
                sysRoleMenusService.save(rmMenus);
            }
            return R.success();
        }


        String dataPermStr = request.getParameter("dataPermStr");
        List<Map> aBean = JSON.parseArray(dataPermStr, Map.class);
        // 绑定新的关联关系
        List<SysRoleMenus> roleMenusList = new ArrayList<>();
        for (Map map : aBean) {
            String menuId = map.get("id").toString();
            String menuCode = map.get("code").toString();
            String dataPerm = map.get("dataPerm").toString();
            SysRoleMenus rmMenus = new SysRoleMenus();
            rmMenus.setId(UUID.get());
            rmMenus.setMenuId(menuId);
            rmMenus.setRoleId(sysRoles.getId());
            rmMenus.setMenuCode(menuCode);
            rmMenus.setDataPerm(dataPerm);
            rmMenus.setUpdateTime(DateUtils.getTimeNow());
            sysRoleMenusService.save(rmMenus);
        }
        return R.success();


    }


    /**
     * 【API】-----【S2006】
     * 根据角色id获取角色关联的菜单信息
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return
     */
    @Log(value = "获取角色关联权限", type = "1")
    @PostMapping("/getRoleCheckedIds")
    public R<List<String>> getRoleCheckedIds(HttpServletRequest request, HttpServletResponse response) {
        String roleId = request.getParameter("roleId");

        QueryWrapper<SysRoleMenus> eWrapper = new QueryWrapper<>();
        eWrapper.eq("role_id", roleId);
        List<SysRoleMenus> roleMenuList = sysRoleMenusService.list(eWrapper);

        List<String> idList = new ArrayList<>();
        for (SysRoleMenus roleMenus : roleMenuList) {
            idList.add(roleMenus.getMenuId());
        }
        return R.success(idList);
    }

    /**
     * 【API】-----【S2006】
     * 根据角色id获取角色关联的菜单信息
     *
     * @param request  [请求信息]
     * @param response [响应信息]
     * @return
     */
    @Log(value = "获取角色关联权限", type = "1")
    @PostMapping("/getRoleCheckedIds2")
    public R<List<SysRoleMenus>> getRoleCheckedIds2(HttpServletRequest request, HttpServletResponse response) {
        String roleId = request.getParameter("roleId");
        QueryWrapper<SysRoleMenus> eWrapper = new QueryWrapper<>();
        eWrapper.eq("role_id", roleId);
        List<SysRoleMenus> roleMenuList = sysRoleMenusService.list(eWrapper);
        return R.success(roleMenuList);
    }


    /**
     * 【API】-----【S2008】
     * 批量删除角色信息
     *
     * @param request
     * @param response
     * @return
     */
    @Log(value = "删除角色信息", type = "1")
    @PostMapping("/delete")
    public R deleteBatch(HttpServletRequest request, HttpServletResponse response, Model model) {
        // 角色绑定菜单---不可删除
        // 角色绑定用户---不可删除
        // 删除 角色表信息
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            sysRolesService.removeById(idString);
        }
        return R.success();

    }


}
